import fetch from 'isomorphic-fetch'

function serialiseObject(obj) {
  const prefix = '?'

  if (obj && Object.keys(obj).length) {
    return prefix + Object.keys(obj).map(key =>
      `${key}=${encodeURIComponent(obj[key])}`,
    ).join('&')
  }

  return ''
}

function getUrl(path, params) {
  const isProd = process.env.NODE_ENV === 'production'
  const server = isProd ? '/m/' : '/api/'

  if (path.startsWith('http:')) {
    return path
  }

  return server + path + serialiseObject(params)
}

function checkStatus(res) {
  if (res.status >= 200 && res.status < 300) {
    return res
  }

  const error = new Error(res.statusText)
  error.res = res
  throw error
}

function getHeaders() {
  return {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  }
}

const http = {
  async get(path, params) {
    const url = getUrl(path, params)
    const options = {
      method: 'GET',
      headers: getHeaders(),
    }

    try {
      const response = await fetch(url, options)
      const checked = await checkStatus(response)
      return checked.json()
    } catch (err) {
      throw new Error(err)
    }
  },

  async post(path, payload) {
    const url = getUrl(path)
    const options = {
      method: 'POST',
      headers: getHeaders(),
      body: JSON.stringify(payload),
    }

    try {
      const response = await fetch(url, options)
      const checked = await checkStatus(response)
      return checked.json()
    } catch (err) {
      throw new Error(err)
    }
  },
}

export default http
